const { Wechaty,MediaMessage,Room,Contact,FriendRequest } = require('wechaty')

const bot = Wechaty.instance();

const HELPER_CONTACT_NAME="订阅公众号"
const HELPER_CONTACT_NAME2="桔小秘"


// 获取二维码
bot.on('scan', (url, code) => log(`登陆二维码: ${code} \n ${url}`))

// 监听用户登录成功
bot.on('login',async user => {

    log(`用户 ${user} 已经登陆了`);

    createDingRoom();
    

    // getRoomMem();

})


//  监听机器人是否发生错误
bot.on('error', async (Wechaty, error) => {


    log(`\n\n机器人 ${Wechaty} 发生错误 ${error} \n`)
})


//  监听退出微信
bot.on('logout', async user => {


    log(`\n\n${user} 已经退出微信 \n`)
})



// 监听新消息
bot.on('message', async m => {

    if (/^ding$/i.test(m.content())) {
 
        await m.say('hello world')
        log('机器人已经回复: hello world', __dirname)
        
        await m.say(mmsg(__dirname + '/img/a.jpg'))
        log('机器人已经回复: Image')

    } else {
        log(`其他消息--${m.content()}`)
    }

})


// 监听是否有人请求添加你为好友
bot.on('friend', async (contact, request) => {
    if(request){ // 1. request to be friend from new contact
        let result = await request.accept()
        if(result){
            log(`Request from ${contact.name()} is accept succesfully!`)
        } else{
            log(`Request from ${contact.name()} failed to accept!`)
        }
    } else { // 2. confirm friend ship
        log(`new friendship confirmed with ${contact.name()}`)
    }
})


//  监听机器人心跳
// bot.on('heartbeat', async (Wechaty, data) => {

//     log(`\n\机器人 ${Wechaty} 心跳 ${data}\n`)
// })


//  监听是否有任何人加入群聊
bot.on('room-join', async (room, inviteeList, inviter) => {

    const nameList = inviteeList.map(c => c.name()).join(',')

    log(`\n\n群聊 ${room.topic()} 获取新成员 ${nameList}, 被谁邀请 ${inviter}\n`)
})


//  监听是否有任何人改了群聊
bot.on('room-topic', async (room, topic, oldTopic, changer) => {


    log(`\n\n群聊  ${room.topic()} 已经被  ${changer}, 改名为 ${topic}\n`)
})


//  监听是否有任何人离开
bot.on('room-leave', async (room, leaver) => {


    log(`\n\n群聊 ${room.topic()} 成员 ${leaver}, 离开了 ${inviter}\n`)
})








bot.start()

async function createRoom() {

    log("下面我要创建一个群聊");
    

    const contact1 = await Contact.find({ name: '桔小秘' });

    const contact2 = await Contact.find({ name: '订阅公众号' })

    const contactList = [contact1, contact2]

    console.log('Bot', 'contactList: %s', contactList.join(','))

    log(`现在要找人加入群聊 ${Array.isArray(contactList)}`)
    
    
    const testRom = await Room.create(contactList, 'ding')
    
    console.log('Bot', 'createDingRoom() new ding room created: %s', testRom,"\n\n")
    

    //const  testRom = await Room.create(contactList);

    testRom.on('topic', (room, topic, oldTopic, changer) => {

        log(`\n\n机器人群聊  ${room.topic()} 已经被  ${changer}, 改名为 ${topic}\n`)

    })

    log("给这个群聊发送消息")

    await testRom.say(mmsg(__dirname + '/img/a.jpg'))

    log("我要给群聊改名字了")

    await testRom.topic('机器人改名字啦')

}

// 已经成功了
async function getRoomMem() {

    let allRoom=await Room.findAll()
    log(`所有群聊：${allRoom} `)

    log(`${typeof allRoom['测试']}`)

    let testRoom2, testRoom1, testRoom3, testRoom4, testRoom5;
    let roomName = '什么鬼'
    
    try {
        testRoom1 = await Room.find({ topic: roomName });
        testRoom2 = await Room.find({ name: roomName });
        testRoom3 = await Room.findAll({ name: roomName });
        testRoom4 = await Room.findAll({ topic: roomName });
        testRoom5 = await Room.findAll(roomName);

    } catch (error) {
        
    }
    
    if (!testRoom1) {
        log(`找不到 ${roomName} 的群聊 testRoom1`)
    }
    
    if (!testRoom2) {
        log(`找不到 ${roomName} 的群聊 testRoom2`)
    }
    
    if (!testRoom3) {
        log(`找不到 ${roomName} 的群聊 testRoom3`)
    }
    
    if (!testRoom4) {
        log(`找不到 ${roomName} 的群聊 testRoom4`)
    }
    if (!testRoom5) {
        log(`找不到 ${roomName} 的群聊 testRoom5`)
    }

    if (!testRoom1&&!testRoom2&&!testRoom3&&!testRoom4&&!testRoom5) return 
    
    log(`获取 ${roomName} 群聊成功 ${testRoom1}`)

    let memberAll = await testRoom1.memberList()
    
    log(`获取${roomName} 群聊成员成功: ${memberAll}`)

    log(`

        一个名叫'测试’的群聊 ${testRoom1} /n/n

        里面的 群聊成员有 ${memberAll}

    `)
    
    log("给这个群聊发送消息")

    await testRoom1.say(mmsg(__dirname + '/img/a.jpg'))

    log("我要给群聊改名字了")

    await testRoom1.topic('机器人改名字啦')
}


// 创建群
async function createDingRoom() {
    
    log('createDingRoom 执行')
  
    try {

        const contactList = await getContact("two")
  
        if (!contactList) {
            log('Bot  getContact() 没有找到好友')
            return
        }

        log(`好友 ${contactList} 准备加群`)  
  
        const room = await Room.create(contactList, 'ding')
        
        log(`群已经建好啦 : %s ${room}` )
    
        await room.topic('ding - created')
        await room.say('ding - created')
    
        return room
  
    } catch (e) {

        log(`建群异常 : ${e.stack}` )
        throw e
        
    }
}
  

// 获取联系人
async function getContact(type) {

    log('Bot getHelperContact()')
    const contact1= await Contact.find({ name: HELPER_CONTACT_NAME })
    const contact2 = await Contact.find({ name: HELPER_CONTACT_NAME2 })
    
    if (type == "one")return contact1 
    else if (type == "two") return [contact1, contact2]
    
}
  
function log(val) {
    console.log(`\n\n----${val}\n`)
}

function mmsg(val) {
    return new MediaMessage(val)
}

function pm(val) {
    return new Promise(val)
}
